import React, { FC, useState } from 'react'
import { Form, Button, Divider, message, Select, Input, Radio } from 'antd'
import TopHeader, { ListTitle } from '~/components/top-header'
import SuccessModal from '~/components/submit-successfully'
import ProductionVoucher from '~/components/production-voucher'
import { useNavigate, useLocation } from 'react-router-dom'
import { queryCastItems, handleTake, queryWaitCastItems } from '~/api/receive-property-api'
import { getUserInfo } from '~/mock/user/userinfo'
import { ReceiveReason, WhereaboutsItemsMap } from '~/constants'
import UploadCom from '~/components/my-upload'
import useGetMembers from '~/hooks/useGetMembers'
import useGetDepartMents from '~/hooks/useGetDepartMents'

import { FooterAction } from './styled'
import WaitingList from './container/waiting-list'
import MovedList from './container/moved-list'
import PropertySelect from './components/property-involved-select'

const { Option } = Select
const { TextArea } = Input
const docs = new Map()
const userPics = new Map()
const isSpecialized = ['KEEPER'].includes(JSON.parse(localStorage.getItem('u')!).roles[0])

const PropertyInvolved: FC = () => {
  const [form] = Form.useForm()
  const navigate = useNavigate()
  const { state } = useLocation()
  const [successVisible, setSuccessVisible] = useState(false)
  const [certificateVisible, setCertificateVisible] = useState(false)
  const [selectVisible, setSelectVisible] = useState(false)
  const [isShowRemark, setIsShowRemark] = useState(false)
  const [isKind, setIsKind] = useState(false)
  const [isShowWhereabouts, setIsShowWhereabouts] = useState(false)
  const [castItems, setCastItems] = useState([])
  const [departmentCode, setDepartmentCode] = useState(state ? (state as any).caseDepartmentCode! : '')
  const receiveMembers = useGetMembers(departmentCode)
  const departMents = useGetDepartMents()
  const [selectedItems, setSelectedItems] = useState<any>([])
  const { validateFields } = form

  const {
    batchNo,
    caseNo,
    caseName,
    caseDepartmentName,
    caseDepartmentCode,
    caseCompanyName,
    caseState,
    createCompanyName,
    createDepartmentName,
    takeUserName,
    takeReason,
    takeDepartmentName,
    whereabouts,
    whereaboutsRemark,
    takeItemFlag
  }: any = state

  const isWait = caseState === 1

  const handleGetCastItems = async (value?: any) => {
    const userInfo = getUserInfo()
    if (isWait) {
      const { data } = await queryWaitCastItems({
        ...userInfo,
        ...value,
        caseNo
      })
      setCastItems(data)
    } else {
      const { data } = await queryCastItems({
        ...userInfo,
        ...value,
        batchNo
      })
      console.log('datadatadata', data)
      setCastItems(data)
    }
  }

  const onClickBorrowCertficate = async (preview?: boolean) => {
    const userInfo = getUserInfo()
    console.log('selectedItems', selectedItems)
    if (!selectedItems.length) return message.error('请至少选择一个涉案财物')
    const {
      takeReason,
      takeUserNo,
      whereabouts,
      whereaboutsRemark,
      takeItemFlag,
      takeDepartmentCode,
      takeDepartmentName
    } = await validateFields()
    const { data } = await handleTake({
      ...userInfo,

      items: selectedItems.map((item: any) => {
        return {
          number: item.itemStock.receiveNumber || item.itemStock.currentNumber,
          serialNo: item.itemStock.serialNo,
          unitName: item.itemStock.unitName
        }
      }),
      caseName,
      caseNo,
      paperDir: 0,
      preview: !!preview,
      docs: [...docs.values()],
      userPics: [...userPics.values()],
      takeCompanyCode: departMents.find(
        (item: any) => item.departmentCode === (takeDepartmentCode || caseDepartmentCode)
      )?.companyCode,
      takeCompanyName: departMents.find(
        (item: any) => item.departmentCode === (takeDepartmentCode || caseDepartmentCode)
      )?.companyName,
      takeDepartmentCode: departMents.find(
        (item: any) => item.departmentCode === (takeDepartmentCode || caseDepartmentCode)
      )?.departmentCode,
      takeDepartmentName: departMents.find(
        (item: any) => item.departmentCode === (takeDepartmentCode || caseDepartmentCode)
      )?.departmentName,
      takeReason,
      takeUserName: receiveMembers.find((item: any) => item.userNo === takeUserNo).userName,
      takeUserNo,
      whereabouts: takeReason === 'GIVE_BACK' ? 'GIVE_BACK' : whereabouts,
      whereaboutsRemark,
      takeItemFlag
    })
    window.open(data.url)
    if (preview) return
    setSuccessVisible(true)
  }

  const headData = [
    {
      childen: [
        {
          label: '案件编号:',
          value: caseNo
        },
        { label: '案件名称:', value: caseName }
      ]
    },
    {
      childen: [
        { label: '办案单位:', value: caseCompanyName || createCompanyName },
        { label: '办案部门:', value: caseDepartmentName || createDepartmentName }
      ]
    }
  ]

  console.log('departMents', departMents)

  return (
    <div>
      <TopHeader headData={headData} />
      <ListTitle />
      <Divider />
      <main style={{ marginTop: 21 }}>
        {isWait ? (
          <WaitingList
            setSelectedItems={setSelectedItems}
            selectedItems={selectedItems}
            handleGetCastItems={handleGetCastItems}
            setSelectVisible={setSelectVisible}
          />
        ) : (
          <MovedList handleGetCastItems={handleGetCastItems} castItems={castItems} />
        )}

        <h3>领取信息</h3>
        <Divider />
        <Form validateTrigger="onBlur" form={form}>
          <Form.Item
            rules={[{ required: isWait, message: '请选择领取部门' }]}
            name="takeDepartmentName"
            label="领取部门"
            initialValue={caseDepartmentName || createDepartmentName}
          >
            {isWait ? (
              <Select
                showSearch
                optionFilterProp="children"
                filterOption={(input, option) => option!.children.toLowerCase().indexOf(input.toLowerCase()) >= 0}
                onChange={(value: string) => {
                  setDepartmentCode(value)
                }}
                dropdownMatchSelectWidth={false}
                placeholder="请选择领取部门"
                style={{ width: 200 }}
              >
                {departMents.map((item: any, index: number) => (
                  <Option key={index} value={item.departmentCode}>
                    {item.departmentName}
                  </Option>
                ))}
              </Select>
            ) : (
              <span>{takeDepartmentName}</span>
            )}
          </Form.Item>
          <Form.Item rules={[{ required: isWait, message: '请选择领取人员' }]} name="takeUserNo" label="领取人员">
            {isWait ? (
              <Select showSearch
                      optionFilterProp="children"
                      filterOption={(input, option) => option!.children.toLowerCase().indexOf(input.toLowerCase()) >= 0}
                      placeholder="请选择领取人员" style={{ width: 200 }}>
                {receiveMembers.map((item: any, index: number) => (
                  <Option key={index} value={item.userNo}>
                    {item.userName}
                  </Option>
                ))}
              </Select>
            ) : (
              <span>{takeUserName}</span>
            )}
          </Form.Item>
          <Form.Item rules={[{ required: isWait, message: '请选择领取事由' }]} name="takeReason" label="领取事由">
            {isWait ? (
              <Select
                onChange={(value: string) => {
                  setIsShowWhereabouts(value === 'TRANSFER_WITH_CASE')
                }}
                placeholder="请选择领取事由"
                style={{ width: 200 }}
              >
                <Option value="GIVE_BACK">发还</Option>
                <Option value="TRANSFER_WITH_CASE">随案移交</Option>
              </Select>
            ) : (
              <span>{ReceiveReason.get(takeReason)}</span>
            )}
          </Form.Item>
          {isShowWhereabouts && (
            <Form.Item rules={[{ required: isWait, message: '请选择物品去向' }]} name="whereabouts" label="物品去向">
              {isWait ? (
                <Select
                  onChange={(val: string) => {
                    setIsShowRemark(!['GIVE_BACK', 'TRANSFER_CASE_DEP'].includes(val))
                    setIsKind(['TRANSFER_CASE_DEP'].includes(val))
                  }}
                  placeholder="请选择物品去向"
                  style={{ width: 200 }}
                >
                  {[...WhereaboutsItemsMap].map(([key, value], index) => (
                    <Option key={index} value={key}>
                      {value}
                    </Option>
                  ))}
                </Select>
              ) : (
                <span>{WhereaboutsItemsMap.get(whereabouts)}</span>
              )}
            </Form.Item>
          )}
          {!isSpecialized && isKind && (
            <Form.Item
              initialValue={0}
              rules={[{ required: isWait, message: '请选择是否实物' }]}
              name="takeItemFlag"
              label="是否为实物"
            >
              {isWait ? (
                <Radio.Group>
                  <Radio value={1}>非实物</Radio>
                  <Radio value={0}>实物</Radio>
                </Radio.Group>
              ) : (
                <span>{takeItemFlag ? '非实物' : '实物'}</span>
              )}
            </Form.Item>
          )}
          {isShowRemark && (
            <Form.Item name="whereaboutsRemark" label="备注">
              {isWait ? <TextArea style={{ width: 200 }} /> : <span>{whereaboutsRemark}</span>}
            </Form.Item>
          )}
        </Form>
        <h3>上传法律文书</h3>
        <Divider />
        <UploadCom
          frontend="frontendedoc"
          onSuccess={({ storeId, name, files }: any) => {
            console.log('files', files)
            docs.set(files.name, { storeId, name })
          }}
          onRemove={(file: any) => {
            docs.delete(file.name)
            console.log('onRemove', file)
          }}
          title="上传法律文书"
        />
        <h3>领取人拍照</h3>
        <Divider />
        <UploadCom
          frontend="frontendepic"
          onSuccess={({ storeId, name, files }: any) => {
            console.log('files', files)
            userPics.set(files.name, { storeId, name })
          }}
          onRemove={(file: any) => {
            userPics.delete(file.name)
            console.log('onRemove', file)
          }}
          title="领取人拍照"
        />
        <FooterAction>
          {isWait ? (
            <div>
              <Button onClick={() => navigate(-1)}>返回</Button>
              <Button
                onClick={() => {
                  onClickBorrowCertficate(true)
                }}
                style={{ marginLeft: 8 }}
              >
                预览领取凭证
              </Button>
              <Button
                onClick={() => {
                  onClickBorrowCertficate()
                }}
                style={{ marginLeft: 8 }}
                type="primary"
              >
                制作领取凭证
              </Button>
            </div>
          ) : (
            <Button onClick={() => navigate(-1)}>返回</Button>
          )}
        </FooterAction>
      </main>
      <SuccessModal visible={successVisible} />
      <PropertySelect
        setSelectedItems={setSelectedItems}
        castItems={castItems}
        setSelectVisible={setSelectVisible}
        visible={selectVisible}
        selectedItems={selectedItems}
        handleGetCastItems={handleGetCastItems}
      />
      <ProductionVoucher
        onOk={() => {
          setCertificateVisible(false)
        }}
        onCancel={() => {
          setCertificateVisible(false)
        }}
        visible={certificateVisible}
      />
    </div>
  )
}

export default PropertyInvolved
